package com.interview.communication;

import org.junit.Test;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * BlockingQueue 阻塞队列方式的单元测试
 */
public class BlockingQueueExampleTest {

    @Test
    public void testBlockingQueueDemo() throws InterruptedException {
        System.out.println("===== BlockingQueue 测试开始 =====");
        long startTime = System.currentTimeMillis();
        
        BlockingQueueExample.demo();
        
        long endTime = System.currentTimeMillis();
        System.out.println("===== BlockingQueue 测试完成，耗时: " + (endTime - startTime) + "ms =====\n");
    }

    @Test
    public void testBlockingQueueBasicOperation() throws InterruptedException {
        // 验证阻塞队列的基本操作
        System.out.println("===== 阻塞队列基本操作测试 =====");
        
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
        
        // 测试put和take
        queue.put("item1");
        queue.put("item2");
        System.out.println("队列已满，两个元素已添加");
        
        String item1 = queue.take();
        System.out.println("取出元素: " + item1);
        assertEquals("取出的元素不正确", "item1", item1);

        String item2 = queue.take();
        System.out.println("取出元素: " + item2);
        assertEquals("取出的元素不正确", "item2", item2);
        
        System.out.println("✓ 阻塞队列基本操作验证通过\n");
    }

    @Test
    public void testBlockingQueueProducerConsumer() throws InterruptedException {
        // 验证生产者-消费者模式
        System.out.println("===== 生产者-消费者测试 =====");
        
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(3);
        final int[] itemCount = {0};
        
        // 生产者
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    queue.put(i);
                    itemCount[0]++;
                    System.out.println("生产了: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        // 消费者
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    Integer item = queue.take();
                    System.out.println("消费了: " + item);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        producer.start();
        consumer.start();
        
        producer.join();
        consumer.join();
        
        assertEquals("生产数量不正确", 5, itemCount[0]);
        assertTrue("队列应该为空", queue.isEmpty());
        System.out.println("✓ 生产者-消费者验证通过\n");
    }
}

